package com.pzhu.dormitory.controller;


import com.pzhu.dormitory.utils.R;
import com.pzhu.dormitory.utils.Rb;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

/**
 * @author jiashubing
 * @since 2019/6/25
 */
@RestController
@Api(tags = "稿件")
@RequestMapping("file")
public class ArticleController {

    @ApiOperation("上传附件")
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    public R<Object> uploadFile(@RequestParam("file") @ApiParam(value = "二进制文件流") MultipartFile file) throws FileNotFoundException {
        String fileName = file.getOriginalFilename();
        assert fileName != null;
        fileName = getFileName(fileName);
        if (!file.isEmpty()) {
            String uploadDir = ResourceUtils.getURL("classpath:").getPath() + "/static/upload/";
            //如果目录不存在，自动创建文件夹
            File dir = new File(uploadDir);
            if (!dir.exists()) {
                dir.mkdir();
            }
            String path = uploadDir + File.separator + fileName;
            try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(path))) {
                out.write(file.getBytes());
                out.flush();
                // 返回文件名
                HashMap<String, String> data = new HashMap<>();
                data.put("src", "/upload/" + fileName);
                return Rb.a(Object.class).withData(data).withCode(0).build();
            } catch (FileNotFoundException e) {
                return Rb.a(Object.class)
                        .fail().withMsg("上传文件失败 FileNotFoundException：" + e.getMessage()).build();
            } catch (IOException e) {
                return Rb.a(Object.class)
                        .fail().withMsg("上传文件失败 IOException：" + e.getMessage()).build();
            }
        } else {
            return Rb.a(Object.class)
                    .fail().withMsg("上传文件失败，文件为空").build();
        }
    }

    /**
     * 文件名后缀前添加一个时间戳
     */
    private String getFileName(String fileName) {
        int index = fileName.lastIndexOf(".");
        final SimpleDateFormat sDateFormatted = new SimpleDateFormat("yyyyMMddMass");
        String nowTimeStr = sDateFormatted.format(new Date());
        fileName = fileName.substring(0, index) + "_" + nowTimeStr + fileName.substring(index);
        return fileName;
    }
}
